<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

        <el-form-item label="单位" prop="unit"  v-if="currentType!=2">
          <el-select
          :style="{ width: '100%' }"
          v-model="queryParams.unit"
          placeholder="请选择单位"

          filterable
        >
          <el-option
            v-for="dict in dict.type.device_unit"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        </el-form-item>
        <el-form-item label="量程" prop="ranges" v-if="currentType==1">
          <el-select
          :style="{ width: '100%' }"
          v-model="queryParams.ranges"
          placeholder="请选择量程"
          filterable
        >
          <el-option
            v-for="dict in dict.type.device_range"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        </el-form-item>
        <el-form-item label="更新的时间" prop="time" v-if="currentType==2" >

          <el-select
          :style="{ width: '100%' }"
          v-model="queryParams.time"
          placeholder="请选择量程"
          filterable
        >
          <el-option
            v-for="dict in seconds"
            :key="dict"
            :label="dict"
            :value="dict"
          />
            </el-select>

        </el-form-item>
        <el-form-item label="关联设备id" prop="deviceIds">
          <el-input
            v-model="queryParams.deviceIds"
            placeholder="请输入关联设备id"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:configuration:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:configuration:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:configuration:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:configuration:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="configurationList" @selection-change="handleSelectionChange"
 

      >
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="序号" align="center" prop="id"     type="index"> -->
        <el-table-column label="序号" align="center"  type="index" :index="indexMethod"/>

        <el-table-column label="单位" align="center" prop="unit" >
          <template slot-scope="scope">
                  <dict-tag
                    :options="dict.type.device_unit"
                    :value="scope.row.unit"
                  />
                </template>
        </el-table-column>
        <el-table-column label="量程" align="center" prop="ranges" v-if="currentType!=3">
          <template slot-scope="scope">
                  <dict-tag
                    :options="dict.type.device_range"
                    :value="scope.row.ranges"
                  />
                </template>
        </el-table-column>
        <el-table-column label="更新的时间" align="center" prop="time" v-if="currentType==2" />
        <el-table-column label="关联设备id" align="center" prop="deviceIds" />
        <!-- <el-table-column label="类型" align="center" prop="type" /> -->
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:configuration:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:configuration:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改设备图形参数配置对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <!-- <el-form-item label="曲线的颜色" prop="color" v-if="currentType==1">
            <el-select
          :style="{ width: '100%' }"
          v-model="form.color"
          placeholder="请选择曲线的颜色"
          filterable
        >
          <el-option
            v-for="dict in dict.type.chart_line_color"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>

          </el-form-item> -->

          <el-form-item label="名称" prop="name" >
            <el-input
              v-model="form.name"
              placeholder="请输入名称"
              clearable
            />
          </el-form-item>

          <el-form-item label="单位" prop="unit" >
            <el-select :disabled="currentType==2"
          :style="{ width: '100%' }"
          v-model="form.unit"
          placeholder="请选择单位"
          @change="handleChangeUnit"

          filterable
        >
          <el-option
            v-for="dict in dict.type.device_unit"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
            <!-- <el-input v-model="form.unit" placeholder="请输入单位" /> -->
          </el-form-item>
          <el-form-item label="量程" prop="ranges" v-if="currentType!=3">
            <!-- <el-input v-model="form.ranges" placeholder="请输入量程" /> -->
            <el-select :disabled="currentType==2"
          :style="{ width: '100%' }"
          v-model="form.ranges"
          @change="handleChangeranges"
          placeholder="请选择量程"
          filterable
        >
          <el-option
            v-for="dict in dict.type.device_range"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
          </el-form-item>
          <el-form-item label="更新的时间" prop="time" v-if="currentType==2">
            <el-select
          :style="{ width: '100%' }"
          v-model="form.time"
          placeholder="请选择更新时间"
          filterable
        >
          <el-option
            v-for="dict in seconds"
            :key="dict"
            :label="dict"
            :value="dict"
          />
            </el-select>
            <!-- <el-input v-model="form.time" placeholder="请输入更新的时间" /> -->
          </el-form-item>
          <el-form-item label="关联设备" prop="deviceIds">
            <el-popover
            title="选择设备"
            v-model="showPop"

            width="800"
            height="600"
            trigger="click">
            <!-- <el-form>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form> -->
            <el-table  max-height="250" :data="gridData" ref="propTable"   @selection-change="handleSelectionChangePop" :row-key="getRowKeys"    >
              <el-table-column
                type="selection"
                width="55" :reserve-selection="true">
              </el-table-column>

              <el-table-column label="序号" align="center"  type="index"  :index="indexMethod1">

              </el-table-column>
              <el-table-column label="设备归属" align="center" prop="belongName" />
              <el-table-column width="150" property="deviceId" label="设备ID"></el-table-column>
              <el-table-column label="设备地址代号_序号" align="center" prop="systemId" >
                <template slot-scope="scope">
                  <el-button type="text" @click="queryDetail(scope.row)">{{scope.row.systemId }}</el-button>
                </template>
              </el-table-column>
              <el-table-column label="设备类型" align="center" prop="modality">
                <template slot-scope="scope">
                  <dict-tag
                    :options="dict.type.modality_list"
                    :value="scope.row.modality"
                  />
                </template>
              </el-table-column>
              <el-table-column label="显示的名称" align="center" prop="deviceName" />

            </el-table>

            <pagination
              v-show="pop.Total > 0"
              :total="pop.Total"
              :page.sync="pop.queryParams.pageNum"
              :limit.sync="pop.queryParams.pageSize"
              @pagination="getData"
            />

            <div class="mar-top-10" style="overflow: hidden;margin-top:30px;">
              <el-button size="mini" style="float:right" class="FloatRight"   icon='el-icon-circle-close' @click="showPop=false" >取消</el-button>
              <el-button size="mini"  type="success" class="card-title-button"  @click="handleSelectData" style="margin-right:10px;float:right;" icon='el-icon-circle-check'>确定</el-button>
            </div>
            <el-button slot="reference" >选择设备</el-button>
          </el-popover>
          <el-table :data="dataSel" height="250" border >
            <el-table-column label="序号" align="center" width="60"  type="index"  >
              <template slot-scope="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="显示的名称" align="center" prop="deviceName" width="100" />
            <el-table-column label="颜色" align="center" width="100" prop="color" v-if="currentType==1" :key="tableKey">
              
              
              <template slot-scope="scope">
                 <el-select
                  :style="{ width: '100%' }"
                  @change="changeFiremans"
                  v-model="scope.row[scope.column.property]"

                >
                  <el-option
                    v-for="dict in dict.type.chart_line_color"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column width="50" prop="deviceId" label="设备ID"></el-table-column>
            <el-table-column label="设备地址代号_序号" align="center" prop="systemId" >
              <template slot-scope="scope">
                <el-button type="text" @click="queryDetail(scope.row)">{{scope.row.systemId }}</el-button>
              </template>
            </el-table-column>
            <el-table-column label="设备类型" align="center" prop="modality">
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.modality_list"
                  :value="scope.row.modality"
                />
              </template>
            </el-table-column>
            <el-table-column prop="belongName" label="设备归属" ></el-table-column>

          </el-table>

          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>

  <script>
  import { listConfiguration, getConfiguration, delConfiguration, addConfiguration, updateConfiguration } from "@/api/system/chartConfig";
  import {listDevice,listDevsNoPage} from "@/api/system/device";
  export default {
    name: "Configuration",
    dicts: [
    "chart_line_color",
    "device_chart_type",
    "device_range",
    "device_unit",
    "modality_list"
  ],

    data() {
      return {
        tableKey: Math.random,
        currentType:this.$route.query.queryParam,//1趋势图 2柱状图 3仪表图
        seconds:[],
        pop:{
        Total:0,
        queryParams:{
          pageNum:1,
          pageSize:10
        }
      },
      dataSel:[],
      multipleSelection: [],
      showPop:false,
      selectData:[],
      gridData: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 设备图形参数配置表格数据
        configurationList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          color: null,
          unit: null,

          ranges: null,
          time: null,
          deviceIds: null,
          type: this.$route.query.queryParam,
          name: null
        },
        // 表单参数
        form: {

        },
        // 表单校验
        rules: {
          name:[
          { required: true, message: "名称不能为空", trigger: "blur" },
          ],
          color:[
          { required: true, message: "颜色选择不能为空", trigger: "blur" },
          ],
          unit:[
          { required: true, message: "单位选择不能为空", trigger: "blur" },
          ],
          ranges:[
          { required: true, message: "量程选择不能为空", trigger: "blur" },
          ],
          time:[
          { required: true, message: "更新的时间不能为空", trigger: "blur" },
          ]
        }
      };
    },
    watch:{
    showPop(n,o){
      if(n==true){
        this.getData() ;
      }

    }
  },
    created() {
      console.log(this.form.ranges)
      let i=1;
      while(i<61){
        this.seconds.push(i);
        i++;
      }

      this.getList();
    },
    methods: {
      indexMethod1(index) {

return index + 1 + (this.pop.queryParams.pageNum- 1) * this.pop.queryParams.pageSize

  },
  
indexMethod(index) {

    return index + 1 + (this.queryParams.pageNum- 1) * this.queryParams.pageSize

      },
      changeFiremans() {
      this.tableKey = Math.random()
    },
      queryDetail(row){
      this.open=false;
      this.$router.push({ path: '/system/device-data/index', params: {systemId:row.systemId,modality:row.modality}} )
    },
      handleChangeUnit(val){
        if(this.currentType!=3){
          this.form.ranges= val;
        }

      },
      handleChangeranges(val){
        this.form.unit= val;

      },
      handleCurrentChange(val) {
      // this.$refs.popTable.togglerRowSelection(val);
    },
      getRowKeys(row) {
      return row.deviceId
    },
      handleSelectData(){	//确认触发事件
      this.dataSel=[];
      this.dataSel=this.multipleSelection;
      // console.log(this.dataSel)
      if(this.currentType ==1){
        this.dataSel.forEach(item=>{
            item.color="red";
        })
      }
      console.log(this.dataSel )
      this.showPop = false
    },
         /** 查询设备列表 */
    getData() {
      this.loading = true;
      listDevice(this.pop.queryParams).then((response) => {
        this.gridData=[];
        this.gridData = response.rows;
        this.pop.Total = response.total;
        this.loading = false;
        if(this.gridData && this.gridData.length>0){
          this.$nextTick(()=>{
            this.toggleRowSelection( )

          });

        }
      });
    },
    async toggleRowSelection () {
      this.gridData.forEach(item=>{
          let c = this.dataSel.find(data => {
            return item.deviceId == data.deviceId // 注意这里寻找的字段要唯一，示例仅参考
          })
          if(c){
            this.$refs.propTable.toggleRowSelection(item,true);
          }else{

          }

      })

    },
      handleSelectionChangePop(val){
      //   if (val.length > 1) {
      //   this.$refs.propTable.clearSelection();
      //   this.$refs.propTable.toggleRowSelection(val[val.length - 1]);
      //   this.multipleSelection = [val[val.length - 1]];

      // }else{
        this.multipleSelection=val ;
      // }

    },
      /** 查询设备图形参数配置列表 */
      getList() {
        this.loading = true;
        listConfiguration(this.queryParams).then(response => {
          this.configurationList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          color: null,
          unit: null,
          ranges: null,
          time: null,
          deviceIds: null,
          type: null,
          name: null
        };
        this.dataSel=[];
      if(this.$refs.propTable){
        this.$refs.propTable.clearSelection()
      }

        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },

      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加设备图形参数配置";

        // this.getDic(this.dict.type.device_unit,2)
        this.form.ranges=(this.currentType=="2")?"2":null;
        this.form.unit=(this.currentType=="2")?"2":null;


      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getConfiguration(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改设备图形参数配置";

          listDevsNoPage({"deviceIds":this.form.deviceIds}).then(res=>{
          // var alarmsList = res.data;
          // this.dataSel== res.data;
          this.dataSel=res.data.map(item=>{
            let color =null;
            if(this.form.color){
              this.form.color.split(",").map(cl=>{
                console.log(cl)
                 if(item.deviceId ==  cl.split(":")[0]) {
                  color = cl.split(":")[1];
                 }
              })
            }

            return {color:color,deviceId:item.deviceId,systemId:item.systemId,modality:item.modality,deviceName:item.deviceName,belongName:item.belongName}
          });

        })

        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {

            if(this.dataSel && this.dataSel.length>0){

              this.form.deviceIds = this.dataSel.map(item=>{

                return item.deviceId;
              }).toString();
              if(this.currentType ==1){

                this.form.color = this.dataSel.map(item=>{
                  return item.deviceId+":"+item.color;
                }).toString();
              }
              // this.form.name =this.dataSel[0].deviceName;
              this.form.type=this.currentType;
          }else{
            this.$message.error("请选择关联设备");
            return;
          }

            if (this.form.id != null) {
              updateConfiguration(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addConfiguration(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除设备图形参数配置编号为"' + ids + '"的数据项？').then(function() {
          return delConfiguration(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/configuration/export', {
          ...this.queryParams
        }, `configuration_${new Date().getTime()}.xlsx`)
      }
    }
  };
  </script>
<style   lang="scss" >





</style>
